import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import styles from './Layout.less';
import {
  Card, Form, Input, Button, message, Upload, Icon,
} from 'antd';

import GoodsModal from 'components/Content/GoodsModal';
import { imgPrex } from '../../utils/constData';

const FormItem = Form.Item;

@connect(({ padRecomm, loading }) => ({
  padRecomm,
  loading: loading.models.padRecomm,
}))
@Form.create()
export default class LayoutDetail3 extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      detailList: this.props.layoutDetail.detailList,
      layoutId: this.props.layoutDetail.layoutId,

      detail: (this.props.layoutDetail.detailList && this.props.layoutDetail.detailList.length > 0) ?
        this.props.layoutDetail.detailList[0] : {},
      detail1: (this.props.layoutDetail.detailList && this.props.layoutDetail.detailList.length > 0) ?
        this.props.layoutDetail.detailList[1] : {},
      detail2: (this.props.layoutDetail.detailList && this.props.layoutDetail.detailList.length > 0) ?
        this.props.layoutDetail.detailList[2] : {},

      fileList: [],
      fileList1: [],
      fileList2: [],

      goodsModalVisible: false,
      goodsModalVisible1: false,
      goodsModalVisible2: false,

      currentGoodsId: (this.props.layoutDetail.detailList && (this.props.layoutDetail.detailList.length > 0) && (this.props.layoutDetail.detailList[0].goodsId)) ?
        this.props.layoutDetail.detailList[0].goodsId : null,
      currentGoodsName: (this.props.layoutDetail.detailList && (this.props.layoutDetail.detailList.length > 0) && (this.props.layoutDetail.detailList[0].goodsName)) ?
        this.props.layoutDetail.detailList[0].goodsName : null,

      currentGoodsId1: (this.props.layoutDetail.detailList && (this.props.layoutDetail.detailList.length > 1) && (this.props.layoutDetail.detailList[1].goodsId)) ?
        this.props.layoutDetail.detailList[1].goodsId : null,
      currentGoodsName1: (this.props.layoutDetail.detailList && (this.props.layoutDetail.detailList.length > 1) && (this.props.layoutDetail.detailList[1].goodsName)) ?
        this.props.layoutDetail.detailList[1].goodsName : null,

      currentGoodsId2: (this.props.layoutDetail.detailList && (this.props.layoutDetail.detailList.length > 2) && (this.props.layoutDetail.detailList[2].goodsId)) ?
        this.props.layoutDetail.detailList[2].goodsId : null,
      currentGoodsName2: (this.props.layoutDetail.detailList && (this.props.layoutDetail.detailList.length > 2) && (this.props.layoutDetail.detailList[2].goodsName)) ?
        this.props.layoutDetail.detailList[2].goodsName : null,
    }
  }


  componentWillReceiveProps(nextProps) {
    if (nextProps.layoutDetail != this.props.layoutDetail) {
      this.props.form.resetFields();
      this.setState({
        detailList: nextProps.layoutDetail.detailList,
        layoutId: nextProps.layoutDetail.layoutId,

        detail: (nextProps.layoutDetail.detailList && nextProps.layoutDetail.detailList.length > 0) ?
          nextProps.layoutDetail.detailList[0] : {},
        detail1: (nextProps.layoutDetail.detailList && nextProps.layoutDetail.detailList.length > 0) ?
          nextProps.layoutDetail.detailList[1] : {},
        detail2: (nextProps.layoutDetail.detailList && nextProps.layoutDetail.detailList.length > 0) ?
          nextProps.layoutDetail.detailList[2] : {},

        fileList: [],
        fileList1: [],
        fileList2: [],

        goodsModalVisible: false,
        goodsModalVisible1: false,
        goodsModalVisible2: false,

        currentGoodsId: (nextProps.layoutDetail.detailList && (nextProps.layoutDetail.detailList.length > 0) && (nextProps.layoutDetail.detailList[0].goodsId)) ?
          nextProps.layoutDetail.detailList[0].goodsId : null,
        currentGoodsName: (nextProps.layoutDetail.detailList && (nextProps.layoutDetail.detailList.length > 0) && (nextProps.layoutDetail.detailList[0].goodsName)) ?
          nextProps.layoutDetail.detailList[0].goodsName : null,

        currentGoodsId1: (nextProps.layoutDetail.detailList && (nextProps.layoutDetail.detailList.length > 1) && (nextProps.layoutDetail.detailList[1].goodsId)) ?
          nextProps.layoutDetail.detailList[1].goodsId : null,
        currentGoodsName1: (nextProps.layoutDetail.detailList && (nextProps.layoutDetail.detailList.length > 1) && (nextProps.layoutDetail.detailList[1].goodsName)) ?
          nextProps.layoutDetail.detailList[1].goodsName : null,

        currentGoodsId2: (nextProps.layoutDetail.detailList && (nextProps.layoutDetail.detailList.length > 2) && (nextProps.layoutDetail.detailList[2].goodsId)) ?
          nextProps.layoutDetail.detailList[2].goodsId : null,
        currentGoodsName2: (nextProps.layoutDetail.detailList && (nextProps.layoutDetail.detailList.length > 2) && (nextProps.layoutDetail.detailList[2].goodsName)) ?
          this.props.layoutDetail.detailList[2].goodsName : null,
      })

    }
  }

  componentDidMount() {

  }

  _goodsSearch(fieldsValue) {
    console.log(1111111111);
    this.props.goodsSearch(fieldsValue)
  }

  _queryDetailList() {
    this.props.dispatch({
      type: 'padRecomm/fetchLayoutDetail',
      payload: { layoutId: this.state.layoutId },
      callback: (data) => this._setDetail(data)
    })
  }

  _setDetail(data) {
    console.log('详情返回', data);

    this.setState({ fileList: [], fileList1: [], fileList2: [], detail: data, })
  }


  _onRemove(type, file) {
    this.setState({ fileList: [] })
    this.props.form.setFieldsValue({ name: (this.state.detail && this.state.detail.pageImg) ? this.state.detail.pageImg : null })
  }

  normFile = (e) => {
    const isLt1M = e.file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      this.setState({ fileList: [], file: null })
      return (this.state.detail && this.state.detail.pageImg) ? this.state.detail.pageImg : null;
    }

    if (e.fileList && e.fileList.length > 0) {
      return e && e.file;
    } else {
      return null;
    }
  }

  _onRemove1(type, file) {
    this.setState({ fileList1: [] })
    this.props.form.setFieldsValue({ name1: (this.state.detail1 && this.state.detail1.pageImg) ? this.state.detail1.pageImg : null })
  }

  normFile1 = (e) => {
    const isLt1M = e.file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      this.setState({ fileList1: [], file1: null })
      return (this.state.detail1 && this.state.detail1.pageImg) ? this.state.detail1.pageImg : null;
    }

    if (e.fileList && e.fileList.length > 0) {
      return e && e.file;
    } else {
      return null;
    }
  }

  _onRemove2(type, file) {
    this.setState({ fileList2: [] })
    this.props.form.setFieldsValue({ name2: (this.state.detail2 && this.state.detail2.pageImg) ? this.state.detail2.pageImg : null })
  }

  normFile2 = (e) => {
    const isLt1M = e.file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      this.setState({ fileList2: [], file2: null })
      return (this.state.detail2 && this.state.detail2.pageImg) ? this.state.detail2.pageImg : null;
    }

    if (e.fileList && e.fileList.length > 0) {
      return e && e.file;
    } else {
      return null;
    }
  }

  _beforeUpload(type, file) {
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      message.error('图片大小不能超过1M');
      return false;
    }
    this.setState({ fileList: [file] })
    this.props.form.setFieldsValue({ name: file });
    return false;
  }

  _beforeUpload1(type, file) {
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      message.error('图片大小不能超过1M');
      return false;
    }

    this.setState({ fileList1: [file] })

    this.props.form.setFieldsValue({ name1: file });
    return false;
  }

  _beforeUpload2(type, file) {
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      message.error('图片大小不能超过1M');
      return false;
    }

    this.setState({ fileList2: [file] })

    this.props.form.setFieldsValue({ name2: file });
    return false;
  }

  _setModalVisible(type, flag) {
    this._goodsSearch();
    this.setState({ goodsModalVisible: flag })
  }

  _setModalVisible1(type, flag) {
    this._goodsSearch();
    this.setState({ goodsModalVisible1: flag })
  }

  _setModalVisible2(type, flag) {
    this._goodsSearch();
    this.setState({ goodsModalVisible2: flag })
  }


  _goodsOk(type, checkedData) {
    console.log(checkedData)
    this.props.form.setFieldsValue({ goodsName: checkedData[0].goods_name })
    this.props.form.setFieldsValue({ goodsId: checkedData[0].goods_id })

    this.setState({ currentGoodsId: checkedData[0].goods_id, currentGoodsName: checkedData[0].goods_name })

    this._setModalVisible(0, false)
  }

  _goodsOk1(type, checkedData) {
    console.log(checkedData)
    this.props.form.setFieldsValue({ goodsName1: checkedData[0].goods_name })
    this.props.form.setFieldsValue({ goodsId1: checkedData[0].goods_id })

    this.setState({ currentGoodsId1: checkedData[0].goods_id, currentGoodsName1: checkedData[0].goods_name })

    this._setModalVisible1(0, false)
  }

  _goodsOk2(type, checkedData) {
    console.log(checkedData)
    this.props.form.setFieldsValue({ goodsName2: checkedData[0].goods_name })
    this.props.form.setFieldsValue({ goodsId2: checkedData[0].goods_id })

    this.setState({ currentGoodsId2: checkedData[0].goods_id, currentGoodsName2: checkedData[0].goods_name })

    this._setModalVisible2(0, false)
  }

  _saveDetail() {
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) return;
      let values = {};

      if (this.state.fileList && (this.state.fileList.length > 0)) {
        values['name'] = this.state.fileList[0];
      }

      values['layoutId'] = this.state.layoutId;
      values['goodsId'] = fieldsValue.goodsId;
      values['recommMsg'] = fieldsValue.recommMsg;
      values['weight'] = fieldsValue.weight;
      values['detailId'] = fieldsValue.detailId;



      console.log('_saveDetail', values)
      if (values.detailId) {
        this.props.dispatch({
          type: 'padRecomm/editLayoutDetail',
          payload: values,
          callback: () => this._saveDetail1()
        })
      } else {
        this.props.dispatch({
          type: 'padRecomm/addLayoutDetail',
          payload: values,
          callback: () => this._saveDetail1()
        })
      }
    })
  }

  _saveDetail1() {
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) return;

      let values1 = {};
      if (this.state.fileList1 && (this.state.fileList1.length > 0)) {
        values1['name'] = this.state.fileList1[0];
      }
      values1['layoutId'] = this.state.layoutId;
      values1['detailId'] = fieldsValue.detailId1;
      values1['goodsId'] = fieldsValue.goodsId1;
      values1['recommMsg'] = fieldsValue.recommMsg1;
      values1['weight'] = fieldsValue.weight1;


      console.log('_saveDetail', values1)
      if (values1.detailId) {
        this.props.dispatch({
          type: 'padRecomm/editLayoutDetail',
          payload: values1,
          callback: () => this._saveDetail2()
        })
      } else {
        this.props.dispatch({
          type: 'padRecomm/addLayoutDetail',
          payload: values1,
          callback: () => this._saveDetail2()
        })
      }
    })
  }

  _saveDetail2() {
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) return;

      let values2 = {};
      if (this.state.fileList2 && (this.state.fileList2.length > 0)) {
        values2['name'] = this.state.fileList2[0];
      }
      values2['layoutId'] = this.state.layoutId;
      values2['detailId'] = fieldsValue.detailId2;
      values2['goodsId'] = fieldsValue.goodsId2;
      values2['recommMsg'] = fieldsValue.recommMsg2;
      values2['weight'] = fieldsValue.weight2;


      console.log('_saveDetail', values2)
      if (values2.detailId) {
        this.props.dispatch({
          type: 'padRecomm/editLayoutDetail',
          payload: values2,
          callback: () => { message.success('保存成功！'); this.props.recommPageSearch() }
        })
      } else {
        this.props.dispatch({
          type: 'padRecomm/addLayoutDetail',
          payload: values2,
          callback: () => { message.success('保存成功！'); this.props.recommPageSearch() }
        })
      }
    })
  }


  _cancel() {
    this.props.recommPageSearch()
  }

  render() {
    const { form, record } = this.props;
    const { detail, detail1, detail2 } = this.state;
    return (
      <Card title={(this.props.layoutDetail.layoutStyle == '4') ? '编辑布局（2行(1+2)列）' : (this.props.layoutDetail.layoutStyle == '5') ? '编辑布局（2行（2+1)列）' : '其他'}>
        <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <Form style={{ width: '33%' }}>
              {
                (this.state.fileList.length > 0) ?
                  <div className={styles.layoutImage}>
                    {this.state.fileList[0].name}
                  </div>
                  :
                  <div className={styles.layoutImage}>
                    <img
                      style={{ width: '160px', height: '160px' }}
                      src={(detail && detail.pageImg) ? (imgPrex + detail.pageImg) : require('../../assets/padRecomm/pic0.png')}
                    />
                  </div>
              }
              <FormItem label="" style={{ display: 'none' }}>
                {form.getFieldDecorator('detailId', {
                  initialValue: detail ? detail.detailId : null,
                })(
                  <Input disabled={true} ></Input>
                )}
              </FormItem>
              <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="图片">
                {form.getFieldDecorator('name', {
                  rules: [{ required: true, message: '请选择图片' }],
                  initialValue: detail ? detail.pageImg : null,
                  getValueFromEvent: this.normFile,
                })(
                  <Upload
                    onRemove={(file) => this._onRemove(0, file)}
                    beforeUpload={(file) => this._beforeUpload(0, file)}
                    fileList={this.state.fileList}
                  >
                    <Button >
                      <Icon type="upload" />选择图片
                    </Button>
                  </Upload>
                )}
              </FormItem>
              <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="内容">
                {form.getFieldDecorator('goodsName', {
                  rules: [{ required: true, message: '商品不能为空' }],
                  initialValue: detail ? detail.goodsName : null,
                })(
                  <span>
                    <Input disabled={true} value={this.props.form.getFieldValue('goodsName')} style={{ width: '65%' }}></Input>
                    <Button
                      onClick={() => this._setModalVisible(0, true)}
                    >选择</Button>
                  </span>
                )}
              </FormItem>
              <FormItem label="" style={{ display: 'none' }}>
                {form.getFieldDecorator('goodsId', {
                  initialValue: detail ? detail.goodsId : null,
                })(
                  <Input disabled={true} ></Input>
                )}
              </FormItem>

              <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="推荐语">
                {form.getFieldDecorator('recommMsg', {
                  rules: [{ required: true, message: '推荐语不能为空' }],
                  initialValue: detail ? detail.recommMsg : null,
                })(
                  <Input maxLength={100}></Input>
                )}
              </FormItem>

              <FormItem label="" style={{ display: 'none' }}>
                {form.getFieldDecorator('weight', {
                  initialValue: detail ? detail.weight ? detail.weight : 1 : 1,
                })(
                  <Input disabled={true} ></Input>
                )}
              </FormItem>

            </Form>





            <Form style={{ width: '33%' }}>
              {
                (this.state.fileList1.length > 0) ?
                  <div className={styles.layoutImage}>
                    {this.state.fileList1[0].name}
                  </div>
                  :
                  <div className={styles.layoutImage}>
                    <img
                      style={{ width: '160px', height: '160px' }}
                      src={(detail1 && detail1.pageImg) ? (imgPrex + detail1.pageImg) : require('../../assets/padRecomm/pic0.png')}
                    />
                  </div>
              }
              <FormItem label="" style={{ display: 'none' }}>
                {form.getFieldDecorator('detailId1', {
                  initialValue: detail1 ? detail1.detailId : null,
                })(
                  <Input disabled={true} ></Input>
                )}
              </FormItem>
              <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="图片">
                {form.getFieldDecorator('name1', {
                  rules: [{ required: true, message: '请选择图片' }],
                  initialValue: detail1 ? detail1.pageImg : null,
                  getValueFromEvent: this.normFile1,
                })(
                  <Upload
                    onRemove={(file) => this._onRemove1(0, file)}
                    beforeUpload={(file) => this._beforeUpload1(0, file)}
                    fileList={this.state.fileList1}
                  >
                    <Button >
                      <Icon type="upload" />选择图片
                    </Button>
                  </Upload>
                )}
              </FormItem>
              <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="内容">
                {form.getFieldDecorator('goodsName1', {
                  rules: [{ required: true, message: '商品不能为空' }],
                  initialValue: detail1 ? detail1.goodsName : null,
                })(
                  <span>
                    <Input disabled={true} value={this.props.form.getFieldValue('goodsName1')} style={{ width: '65%' }}></Input>
                    <Button
                      onClick={() => this._setModalVisible1(0, true)}
                    >选择</Button>
                  </span>
                )}
              </FormItem>
              <FormItem label="" style={{ display: 'none' }}>
                {form.getFieldDecorator('goodsId1', {
                  initialValue: detail1 ? detail1.goodsId : null,
                })(
                  <Input disabled={true} ></Input>
                )}
              </FormItem>

              <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="推荐语">
                {form.getFieldDecorator('recommMsg1', {
                  rules: [{ required: true, message: '推荐语不能为空' }],
                  initialValue: detail1 ? detail1.recommMsg : null,
                })(
                  <Input maxLength={100}></Input>
                )}
              </FormItem>

              <FormItem label="" style={{ display: 'none' }}>
                {form.getFieldDecorator('weight1', {
                  initialValue: detail1 ? detail1.weight ? detail.weight : 2 : 2,
                })(
                  <Input disabled={true} ></Input>
                )}
              </FormItem>
            </Form>


            <Form style={{ width: '33%' }}>
              {
                (this.state.fileList2.length > 0) ?
                  <div className={styles.layoutImage}>
                    {this.state.fileList2[0].name}
                  </div>
                  :
                  <div className={styles.layoutImage}>
                    <img
                      style={{ width: '160px', height: '160px' }}
                      src={(detail2 && detail2.pageImg) ? (imgPrex + detail2.pageImg) : require('../../assets/padRecomm/pic0.png')}
                    />
                  </div>
              }
              <FormItem label="" style={{ display: 'none' }}>
                {form.getFieldDecorator('detailId2', {
                  initialValue: detail2 ? detail2.detailId : null,
                })(
                  <Input disabled={true} ></Input>
                )}
              </FormItem>
              <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="图片">
                {form.getFieldDecorator('name2', {
                  rules: [{ required: true, message: '请选择图片' }],
                  initialValue: detail2 ? detail2.pageImg : null,
                  getValueFromEvent: this.normFile2,
                })(
                  <Upload
                    onRemove={(file) => this._onRemove2(0, file)}
                    beforeUpload={(file) => this._beforeUpload2(0, file)}
                    fileList={this.state.fileList2}
                  >
                    <Button >
                      <Icon type="upload" />选择图片
                    </Button>
                  </Upload>
                )}
              </FormItem>
              <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="内容">
                {form.getFieldDecorator('goodsName2', {
                  rules: [{ required: true, message: '商品不能为空' }],
                  initialValue: detail2 ? detail2.goodsName : null,
                })(
                  <span>
                    <Input disabled={true} value={this.props.form.getFieldValue('goodsName2')} style={{ width: '65%' }}></Input>
                    <Button
                      onClick={() => this._setModalVisible2(0, true)}
                    >选择</Button>
                  </span>
                )}
              </FormItem>
              <FormItem label="" style={{ display: 'none' }}>
                {form.getFieldDecorator('goodsId2', {
                  initialValue: detail2 ? detail2.goodsId : null,
                })(
                  <Input disabled={true} ></Input>
                )}
              </FormItem>

              <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="推荐语">
                {form.getFieldDecorator('recommMsg2', {
                  rules: [{ required: true, message: '推荐语不能为空' }],
                  initialValue: detail2 ? detail2.recommMsg : null,
                })(
                  <Input maxLength={20}></Input>
                )}
              </FormItem>

              <FormItem label="" style={{ display: 'none' }}>
                {form.getFieldDecorator('weight2', {
                  initialValue: detail2 ? detail2.weight ? detail.weight : 3 : 3,
                })(
                  <Input disabled={true} ></Input>
                )}
              </FormItem>
            </Form>


          </div>
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <Button type="primary" style={{ marginLeft: '20px' }} onClick={() => this._saveDetail()}>保存</Button>
            <Button type="primary" style={{ marginLeft: '20px' }} onClick={() => this._cancel()}>取消</Button>
          </div>
        </div>


        <GoodsModal goodsModalVisible={this.state.goodsModalVisible}
          channelTree={this.props.channelTree}
          goodsList={this.props.goodsList}
          goodsId={this.state.currentGoodsId}
          goodsName={this.state.currentGoodsName}
          setModalVisible={(type, flag) => this._setModalVisible(type, flag)}
          goodsSearch={(fieldsValue) => this._goodsSearch(fieldsValue)}
          goodsOk={(type, checkedData) => this._goodsOk(type, checkedData)}
        />

        <GoodsModal goodsModalVisible={this.state.goodsModalVisible1}
          channelTree={this.props.channelTree}
          goodsList={this.props.goodsList}
          goodsId={this.state.currentGoodsId1}
          goodsName={this.state.currentGoodsName1}
          setModalVisible={(type, flag) => this._setModalVisible1(type, flag)}
          goodsSearch={(fieldsValue) => this._goodsSearch(fieldsValue)}
          goodsOk={(type, checkedData) => this._goodsOk1(type, checkedData)}
        />

        <GoodsModal goodsModalVisible={this.state.goodsModalVisible2}
          channelTree={this.props.channelTree}
          goodsList={this.props.goodsList}
          goodsId={this.state.currentGoodsId2}
          goodsName={this.state.currentGoodsName2}
          setModalVisible={(type, flag) => this._setModalVisible2(type, flag)}
          goodsSearch={(fieldsValue) => this._goodsSearch(fieldsValue)}
          goodsOk={(type, checkedData) => this._goodsOk2(type, checkedData)}
        />
      </Card>

    );
  }
}